from alipay import AliPay
from django.http import HttpResponseForbidden, JsonResponse
from django.views import View

from apps.orders.models import OrderInfo
from config import settings
from utils.mixins import LoginRequiredJSONMixin
from utils.response_code import RETCODE


class PaymentView(LoginRequiredJSONMixin, View):
    def get(self, request, order_id):
        user = request.user

        # 1. 查订单
        try:
            order = OrderInfo.objects.get(
                order_id=order_id,
                user=user,
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']
            )
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden('订单信息错误')

        # 2. 构建支付对象（使用 settings 中的统一密钥）
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_private_key_string=settings.APP_PRIVATE_KEY,
            alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG,
        )

        # 3. 生成支付链接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=f'小鱼商城订单 {order_id}',
            return_url=settings.ALIPAY_RETURN_URL,
        )

        # 4. 拼接完整的跳转地址
        alipay_url = settings.ALIPAY_URL + "?" + order_string

        # 5. 返回支付链接
        return JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'OK',
            'alipay_url': alipay_url
        })